package com.example.rocketmqdemo.message;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

import java.lang.annotation.Annotation;
import java.util.concurrent.TimeUnit;

/**
 *  监听Rocket的事务消息
 *  两阶段提价事务（2pc）
 */
@Slf4j
@RocketMQTransactionListener
public class CustomerTransactionListener implements RocketMQLocalTransactionListener {

    private static boolean isComplete = true;


    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("监听的本地消息是：${},携带的参数是：${}",message,o);
        int flag = 1;
        switch (flag){
            case 0 -> {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            case 1 ->{
                // 交给检查本地事务的方法进行事务状态的判断
                return RocketMQLocalTransactionState.UNKNOWN;
            }
            case 2 -> {
                return RocketMQLocalTransactionState.COMMIT;
            }
        }
        return null;
    }

    /**
     * 回查本地事务状态，根据这次回查的结果来决定此次事务是提交还是回滚；
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 执行判断的业务代码

        // 判断事务的状态
        if (isComplete) {
            return RocketMQLocalTransactionState.COMMIT;
        }else {
            isComplete = true;
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
